package com.trainingcloud.ctrl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.trainingcloud.mapper.VideoMapper;
import com.trainingcloud.pojo.Video;
import com.trainingcloud.utils.MyFileUtil;
import com.trainingcloud.utils.MyVideoUtil;
import com.trainingcloud.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

/**
 * <p>
 * 视频列表 前端控制器
 * </p>
 *
 * @author 纸鹤
 * @since 2022-10-11
 */
@RestController
public class VideoController {

    @Autowired
    private MyVideoUtil videoUtil;

    @Autowired
    private VideoMapper videoMapper;

    @RequestMapping("/addVideo")
    public ResultUtil addVideo(MultipartFile file, Video video) {
        ResultUtil ok = ResultUtil.ok();
        String videourl = MyFileUtil.fileUpload("video", file);
        video.setVideoUrl(videourl);
        videoMapper.insert(video);
        ok.setData(videourl);
        return ok;
    }

    @RequestMapping("/getVideos")
    public ResultUtil getVideos(Video video) {
        ResultUtil ok = ResultUtil.ok();
        QueryWrapper<Video> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", video.getStatus());
        if (video.getRelationGroupId() != null) {
            queryWrapper.eq("relation_group_id", video.getRelationGroupId());
        }
        List<Video> videos = videoMapper.selectList(queryWrapper);
        ok.setData(videos);
        return ok;
    }

    @RequestMapping("/getVideo")
    public void getVideo(String url, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        //1.获取视频文件的地址
        Path path = Paths.get(MyFileUtil.BASE_URL + "/" + url);
        System.out.println("-----------------------------------------------");
        System.out.println(url);
        //2.判断文件是否存在
        if (Files.exists(path)) {
            //3.获取文件类型
            String mtype = Files.probeContentType(path);
            if (StringUtils.hasText(mtype)) {
                //设置返回流的类型
                response.setContentType(mtype);
            }
            request.setAttribute(MyVideoUtil.FILE_PATH, path);
            videoUtil.handleRequest(request, response);
        } else {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
        }
    }
}


